package com.ruoyi.web.controller.cs;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.vo.AnchorBattleParamReq;
import com.ruoyi.cs.domain.vo.TRobotBehaviorVo;
import com.ruoyi.cs.domain.vo.TRollCyVo;
import com.ruoyi.cs.domain.vo.TUserVo;
import com.ruoyi.cs.mapper.TLogMapper;
import com.ruoyi.cs.mapper.TUserAuthenticationMapper;
import com.ruoyi.cs.mapper.TUserMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.cs.mapper.TUserTgMapper;
import com.ruoyi.cs.service.ITBackpackService;
import com.ruoyi.cs.service.PicUploadService;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javafx.scene.control.ToggleButton;
import jdk.nashorn.internal.runtime.ConsString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cs.service.ITUserService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisCluster;

/**
 * 用户信息Controller
 *
 * @author ruoyi
 * @date 2021-03-25
 */
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/cs/user")
@SuppressWarnings("all")
public class TUserController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TUserController.class);

    @Autowired
    private ITUserService tUserService;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ITBackpackService tbBackpackService;
    @Autowired
    private TLogMapper tLogMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private TUserTgMapper tUserTgMapper;

    @Value("${ruoyi.picpath}")
    private String picpath;

    @Value("${token.expireTime}")
    Long expireTime;

    @Value("${ruoyi.cos-fileUrl}")
    private String cosfileUrl;
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    @Autowired
    private RedisCache redisCache;
    /**
     * 后台查询用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('cs:user:listBack')")
    @ApiOperation("后台查询用户信息列表")
    @RequestMapping(name="后台查询用户信息列表",value="listBack",method = RequestMethod.POST)
    public ResponsePageInfo<TUserVo> listBack(@RequestBody TUserVo tUserVo)
    {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null){
            SysUser user = loginUser.getUser();
            if (user != null) {
               SysUser sysUser =  sysUserService.selectUserByUserName(user.getUserName());
               if (sysUser.getUserType().equals("01")) {
                   tUserVo.setUserType("0");
               }
            }
        }
        startPage(tUserVo.getPageNum(),tUserVo.getPageSize(),"create_time desc");
        List<TUserVo> list = tUserService.userListBack(tUserVo);
        return toResponsePageInfo(list);
    }
    /**
     * 用户统计
     */
    @PreAuthorize("@ss.hasPermi('cs:user:count')")
    @ApiOperation("用户统计")
    @RequestMapping(name="用户统计",value="count",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime",value = "开始时间" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime",value = "结束时间" , dataType = "String", paramType = "query", required = false),
    })
    public Response<Map> count(String startTime, String endTime)
    {
        Map map = tUserService.userCount(startTime, endTime);
        return Response.success(map);
    }


    /**
     * 新增主播信息
     */
    @PreAuthorize("@ss.hasPermi('cs:user:add')")
    @ApiOperation("新增主播信息")
    @RequestMapping(name="新增主播信息",value="add",method = RequestMethod.POST)
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    public Response add(@RequestBody TUser tUser)
    {
        try {
            return tUserService.insertTUser(tUser);
        } catch (Exception e) {
            log.error("新增主播信息异常：{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('cs:user:edit')")
    @ApiOperation("修改用户信息")
    @RequestMapping(name="修改用户信息",value="edit",method = RequestMethod.POST)
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    public Response edit(@RequestBody TUser tUser)
    {
        try {
            return tUserService.updateTUser(tUser);
        } catch (Exception e) {
            log.error("编辑用户异常：{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 停用用户信息
     */
    @PreAuthorize("@ss.hasPermi('cs:user:stop')")
    @ApiOperation("停用用户信息")
    @RequestMapping(name="停用用户信息",value="stop",method = RequestMethod.GET)
    @Log(title = "用户信息", businessType = BusinessType.STOP)
    @ApiImplicitParam(name = "userId",value = "用户ID" ,dataType = "String", paramType = "query", required = true)
    public Response stop(String userId)
    {
        try {
            if (StringUtils.isNotEmpty(userId)) {
                return toResponse(tUserService.updateDelFlagTUserByIds(Constants.FAIL,userId));
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("停用用户信息异常:{}",e.getMessage());
            return Response.error();
        }
    }
    /**
     * 启用用户信息
     */
    @PreAuthorize("@ss.hasPermi('cs:user:enable')")
    @ApiOperation("启用用户信息")
    @RequestMapping(name="启用用户信息",value="enable",method = RequestMethod.GET)
    @Log(title = "用户信息", businessType = BusinessType.ENABLE)
    @ApiImplicitParam(name = "userId",value = "用户ID" ,dataType = "String", paramType = "query", required = true)
    public Response<Integer> enable(String userId)
    {
        try {
            if (StringUtils.isNotEmpty(userId)) {
                return toResponse(tUserService.updateDelFlagTUserByIds(Constants.SUCCESS,userId));
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("启用用户信息异常:{}",e.getMessage());
            return Response.error();
        }
    }


    @ApiOperation("后台用户推广详情")
    @RequestMapping(name="后台用户推广详情",value="getUserTGList",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:getUserTGList')")
    public ResponsePageInfo<TUser> getUserTGList(@RequestBody TUser tUser)
    {
        startPage(tUser.getPageNum(),tUser.getPageSize());
        List<TUser> list = tUserService.getUserTGList(tUser.getUserId());
        return toResponsePageInfo(list);
    }

    /**
     * 短信验证码发送
     * @param user
     * @return
     */
    @ApiOperation("短信验证码发送")
    @PreAuthorize("@ss.hasPermi('cs:user:sendNodeBack')")
    @RequestMapping(name="短信验证码发送",value="sendNodeBack",method = RequestMethod.GET)
    @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true)
    public Response sendNodeBack(String userPhone)
    {
        try {
            return tUserService.sendNode(userPhone);
        } catch (Exception e) {
            log.error("短信验证码发送异常:{}",e.getMessage());
            return Response.error();
        }
    }
    /**
     * 用户盲盒对战权限
     * @param user
     * @return
     */
    @ApiOperation("用户盲盒对战权限")
    @PreAuthorize("@ss.hasPermi('cs:user:boxBattlePower')")
    @RequestMapping(name="用户盲盒对战权限",value="boxBattlePower",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "isBattle",value = "是否允许对战" , dataType = "String", paramType = "query", required = true),
    })
    @Log(title = "设置用户盲盒对战权限", businessType = BusinessType.UPDATE)
    public Response<Integer> boxBattlePower(String userId,String isBattle)
    {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(isBattle)) {
            return Response.fail(Constants.FAILCODE,"用户编号和对战权限值不能为空！");
        }
        try {
            return toResponse(tUserService.updateBattlePower(userId,isBattle));
        } catch (Exception e) {
            log.error("用户盲盒对战权限修改异常:{}",e.getMessage());
            return Response.error();
        }
    }


    @ApiOperation("添加机器人")
    @RequestMapping(name = "添加机器人", value = "addRobot", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:addRobot')")
    @Log(title = "添加机器人", businessType = BusinessType.INSERT)
    public Response addRobot(@RequestBody TUser tUser) {
        try {
            return tUserService.addRobot(tUser);
        } catch (Exception e) {
            log.error("添加机器人异常：{}", e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation("删除机器人")
    @RequestMapping(name = "删除机器人", value = "deleteRobot", method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:user:deleteRobot')")
    @Log(title = "删除机器人", businessType = BusinessType.DELETE)
    public Response deleteRobot(String userIds) {
        try {
            int i = tUserService.deleteTUserByIds(userIds);
            if (i < 1) {
                return Response.fail("操作失败");
            }
            return Response.success();
        } catch (Exception e) {
            log.error("删除机器人异常：{}", e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation("编辑机器人")
    @RequestMapping(name = "编辑机器人", value = "editRobot", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:editRobot')")
    @Log(title = "编辑机器人", businessType = BusinessType.UPDATE)
    public Response editRobot(@RequestBody TUser tUser) {
        try {
            return tUserService.editRobot(tUser);
        } catch (Exception e) {
            log.error("编辑机器人异常：{}", e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation("设置机器人行为记录")
    @RequestMapping(name = "设置机器人行为记录", value = "robotBehavior", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:robotBehavior')")
    @Log(title = "设置机器人行为记录", businessType = BusinessType.INSERT)
    public Response robotBehavior(@RequestBody TRobotBehaviorVo tRobotBehaviorVo) {
        try {
            String userIds = tRobotBehaviorVo.getUserId();
            if (StringUtils.isEmpty(userIds)) {
                return Response.fail(Constants.FAILCODE, "用户ID不能为空！");
            }
            String[] ids = userIds.split(",");
//            StringBuilder sb = new StringBuilder();
            Response response = null;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ids.length; i++) {
                TRobotBehaviorVo vo = new TRobotBehaviorVo();
                BeanUtils.copyProperties(tRobotBehaviorVo, vo);
                vo.setUserId(ids[i]);
                Response re = tUserService.robotBehavior(vo);
                if (re.getCode() == Constants.FAILCODE) {
                    response = re;
                } else {
                    response = Response.success("设置成功");
                }
            }
            return response;
        } catch (Exception e) {
            log.error("设置机器人行为记录异常：{}", e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation("查询机器人列表")
    @RequestMapping(name = "查询机器人列表", value = "robotList", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:robotList')")
    public ResponsePageInfo<TUser> robotList(@RequestBody TUser tUser) {
        startPage(tUser.getPageNum(), tUser.getPageSize());
        tUser.setDelFlag(Constants.SUCCESS);
        List<TUser> tUsers = tUserService.selectUserList(tUser);
        return toResponsePageInfo(tUsers);
    }

    @ApiOperation("查询机器人行为列表")
    @RequestMapping(name = "查询机器人行为列表", value = "robotBehaviorList", method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:user:robotBehaviorList')")
    public ResponsePageInfo<TRobotBehavior> tRobotBehaviorList(@RequestBody TRobotBehavior tRobotBehavior) {
        startPage(tRobotBehavior.getPageNum(), tRobotBehavior.getPageSize());
        List<TRobotBehavior> list = tUserService.selectTRobotBehaviorList(tRobotBehavior);
        return toResponsePageInfo(list);
    }

    @ApiOperation("查询机器人总数")
    @RequestMapping(name = "查询机器人总数", value = "robotCount", method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:user:robotCount')")
    public Response<Map> robotCount() {
        String testRobatNum = "0";
        String battleRobatNum = "0";
        List<Map<String, Object>> robatNumberList = tUserService.robatNumber();
        List<Map<String, Object>> testRobat = robatNumberList.stream().filter(map -> map.get("userType").equals(Constants.USERTYPE2)).collect(Collectors.toList());
        List<Map<String, Object>> battleRobat = robatNumberList.stream().filter(map -> map.get("userType").equals(Constants.USERTYPE3)).collect(Collectors.toList());
        if (testRobat.size() > 0) {
            testRobatNum = testRobat.get(0).get("userNum").toString();
        }
        if (battleRobat.size() > 0) {
            battleRobatNum = battleRobat.get(0).get("userNum").toString();
        }
        Map<String, String> map = new HashMap();
        map.put("testRobat", testRobatNum);
        map.put("battleRobat", battleRobatNum);
        return Response.success(map);
    }

    /**
     * 修改主播离职状态
     * @param user
     * @return
     */
    @ApiOperation("主播离职状态调整")
    @PreAuthorize("@ss.hasPermi('cs:user:updateAnchorResignationStatus')")
    @RequestMapping(name="主播离职状态调整",value="updateAnchorResignationStatus",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "anchorResignationStatus",value = "主播离职状态 0 正常 1 离职" , dataType = "String", paramType = "query", required = true),
    })
    @Log(title = "主播离职状态调整", businessType = BusinessType.UPDATE)
    public Response<Integer> updateAnchorResignationStatus(String userId,String anchorResignationStatus)
    {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(anchorResignationStatus)) {
            return Response.fail(Constants.FAILCODE,"用户编号和主播离职状态不能为空！");
        }
        try {
            return toResponse(tUserService.updateAnchorResignationStatus(userId,anchorResignationStatus));
        } catch (Exception e) {
            log.error("主播离职状态调整异常:{}",e.getMessage());
            return Response.error();
        }
    }

    @ApiOperation("主播对战参数设置")
    @PreAuthorize("@ss.hasPermi('cs:user:anchorBattleParamReq')")
    @PutMapping("/anchorBattleParamReq/{userId}")
    @ApiImplicitParam(name = "userId",value = "用户id" ,dataType = "String", paramType = "path", required = true)
    @Log(title = "主播对战参数设置", businessType = BusinessType.UPDATE)
    public Response anchorBattleParamReq(@PathVariable("userId")String userId,@Validated @RequestBody AnchorBattleParamReq anchorBattleParamReq){
        return tUserService.anchorBattleParamReq(userId,anchorBattleParamReq);
    }

    /*---------------------------------------------前端接口-----------------------------------*/

    /**
     * 登录验证
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @CheckSwitch
    @ApiOperation("web登录验证")
    @RequestMapping(name="登录验证",value="common/login",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "userPwd",value = "密码" , dataType = "String", paramType = "query", required = true),
    })
    @Log(title = "登录验证", businessType = BusinessType.INSERT)
    public AjaxResult login(@RequestParam(value = "userPhone",required = true) String userPhone,
                            @RequestParam(value = "userPwd",required = true) String userPwd,
                            @RequestParam(value = "code",required = false) String code)
    {
        try {
            String md5 = Md5Utils.hash(userPwd);
            //手机号是唯一的
            TUser user = tUserMapper.getUserInfoByPhoneV2(userPhone);
            if (user == null || !md5.equals(user.getUserPwd())) {
                return new AjaxResult (Constants.FAILCODE,"请输入正确的账号密码~");
            }
            if(user.getUserType().equals(Constants.USERTYPE0)){
                if(StringUtils.isEmpty(code)){
                    return new AjaxResult (Constants.FAILCODE,"请输入验证码~");
                }
                //短信验证码前缀
                String key = Constants.PHONE_CODE+userPhone;
                //从Redis获取短信验证码
                String code1 = redisCache.getCacheObject(key);
                redisCache.deleteObject(key);
                if (StringUtils.isEmpty(code1) || !code1.equals(code)) {
                    return new AjaxResult(Constants.FAILCODE,"验证码错误!");
                }
            }
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            String loginArea = AddressUtils.getRealAddressByIP(ip);

            AsyncManager.me().execute(AsyncFactory.recordLogininforWeb(userPhone, Constants.SUCCESS, MessageUtils.message("user.login.success")));
            LoginUser loginUser = new LoginUser();
            SysUser sysUser = new SysUser();
            sysUser.setUserName(user.getUserPhone());
            sysUser.setPassword(md5);
            sysUser.setStatus(user.getDelFlag());
            sysUser.setLoginUserId(user.getUserId());
            loginUser.setUser(sysUser);
            loginUser.setExpireTime(expireTime);

            if (!soloLogin)
            {
                // 如果用户不允许多终端同时登录，清除缓存信息
                String userIdKey = Constants.LOGIN_TOKEN_KEY_WEB + loginUser.getUser().getLoginUserId();
                String userKey = redisCache.getCacheObject(userIdKey);
                if (StringUtils.isNotEmpty(userKey))
                {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }
            // 生成token
            String token =  tokenService.createTokenWeb(loginUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN_WEB, token);
            return ajax;
        } catch (Exception e) {
            log.error("登录验证异常:{}",e.getMessage());
            return AjaxResult.error();
        }
    }
    /**
     * 验证码登录验证
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @CheckSwitch
    @ApiOperation("web验证码登录验证(登录注册)")
    @RequestMapping(name="验证码登录验证",value="common/codeLogin",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code",value = "验证码" , dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "tgUserSelfCode",value = "推广码" , dataType = "String", paramType = "query", required = false)
    })
    @Log(title = "验证码登录验证", businessType = BusinessType.INSERT)
    public AjaxResult codeLogin(@RequestParam(value = "userPhone",required = true) String userPhone,
                                @RequestParam(value = "code",required = true) String code,
                                @RequestParam(value = "tgUserSelfCode",required = false) String tgUserSelfCode)
    {
        try {
            //短信验证码前缀
            String key = Constants.PHONE_CODE+userPhone;
            //从Redis获取短信验证码
            String code1 = redisCache.getCacheObject(key);
            if (StringUtils.isEmpty(code1) || !code1.equals(code)) {
                return new AjaxResult(Constants.FAILCODE,"验证码错误!");
            }

            TUser tUser =  tUserMapper.getUserInfoByPhone(userPhone);
            if (tUser == null) {
                boolean tgflag = false;
                String tgUserId = null;
                /**用户不存在则注册操作*/
                tUser = new TUser();
                tUser.setUserPhone(userPhone);
                tUser.setUserName(Constants.USERNAME_PREFIX +CommonUtils.generateRandomString(5));
                //判断该用户是否填写邀请码,并判断邀请码是否正确
                if (StringUtils.isNotEmpty(tgUserSelfCode)) {
                    TUser tgUser = tUserMapper.getUserInfoByCode(tgUserSelfCode);
                    if (tgUser.getDelFlag().equals(Constants.SUCCESS) && (!tgUser.getUserType().equals(2))) {
                        tUser.setUserPromotersId(tgUser.getUserId());
                        tgflag = true;
                        tgUserId = tgUser.getUserId();
                    }
                }
                String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
                tUser.setUserIp(ip);
                tUser.setUserArea(AddressUtils.getRealAddressNameByIP(ip));

                /**现在统一IP地址注册*/
                Long ipusernum = tUserMapper.countUserNumByIP(ip);
                SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("ip_limit_register");
                String limitnum = sysConfig == null ? "1" : sysConfig.getConfigValue();
                if(ipusernum.intValue() > Integer.parseInt(limitnum) ){
                    log.error("防止机器人恶意注册：ip:{},地区:{}",ip,AddressUtils.getRealAddressNameByIP(ip));
                    return new AjaxResult (Constants.FAILCODE,"防止机器人恶意注册，注册失败!");
                }
                //插入用户表中
                String userId = IdUtils.fastUUID().substring(0,8)+DateUtils.dateTimeNow();
//                String userSelfCode = IdUtils.fastUUID().substring(0, 8);
                String userSelfCode = HashUtil.generatePromoCode();
                while (tUserMapper.isPromoCodeExists(userSelfCode) >  0){
                    userSelfCode = HashUtil.generatePromoCode();
                }
                tUser.setUserId(userId);
                tUser.setUserSelfCode(userSelfCode);
                tUser.setUserType(Constants.USERTYPE0);
                tUser.setUserBalance(new BigDecimal(0));
                tUser.setPurchaseQuota(new BigDecimal(0));
                tUser.setUserTotalRecharge(new BigDecimal(0));
                tUser.setCreateTime(DateUtils.getNowDate());
//                user.setUserPwd(Md5Utils.hash(user.getUserPwd()));
                tUser.setIsBattle(Constants.SUCCESS);
                List<String> pics = Arrays.asList(Constants.USERPICS);
                Random random = new Random();
                int index = random.nextInt(pics.size());
                tUser.setUserPic(picpath +cosfileUrl+ pics.get(index));

                tUser.setCommissionRatio(new BigDecimal(0.04));
                tUser.setUserUrl(Constants.USERURLPREFIX+"/"+userSelfCode);
                tUser.setUserSeed(HashUtil.generateUserSeed());
                /**设置推广人推广码*/
                int count =  tUserMapper.insertTUser(tUser);

                //验证码正确则插入用户推广信息记录表
                if (tgflag) {
                    TUserTg tg = new TUserTg();
                    tg.setUserId(tgUserId);
                    tg.setTgUserId(userId);
                    tg.setCreateTime(DateUtils.getNowDate());
                    tUserTgMapper.insertTUserTg(tg);
                }
            }else{
                /**用户存在执行登录操作*/
                if (!(tUser.getDelFlag().equals(Constants.SUCCESS))) {
                    return new AjaxResult (Constants.FAILCODE,"用户账号已关闭,具体请联系客服处理!");
                }
            }

            AsyncManager.me().execute(AsyncFactory.recordLogininforWeb(userPhone, Constants.SUCCESS, MessageUtils.message("user.login.success")));
            LoginUser loginUser = new LoginUser();
            SysUser sysUser = new SysUser();
            sysUser.setUserName(tUser.getUserPhone());
            sysUser.setPassword(tUser.getUserPwd());
            sysUser.setStatus(tUser.getDelFlag());
            sysUser.setLoginUserId(tUser.getUserId());
            loginUser.setUser(sysUser);
            loginUser.setExpireTime(expireTime);
            if (!soloLogin)
            {
                // 如果用户不允许多终端同时登录，清除缓存信息
                String userIdKey = Constants.LOGIN_TOKEN_KEY_WEB + loginUser.getUser().getLoginUserId();
                String userKey = redisCache.getCacheObject(userIdKey);
                if (StringUtils.isNotEmpty(userKey))
                {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }

            // 生成token
            String token =  tokenService.createTokenWeb(loginUser);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN_WEB, token);

            /*删除验证码*/
            redisCache.deleteObject(key);

            return ajax;
        } catch (Exception e) {
            log.error("登录验证异常:{}",e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation("web获取用户信息详细信息")
    @RequestMapping(name="获取用户信息详细信息",value="getInfo",method = RequestMethod.GET)
    public Response<TUser> getInfo()
    {
        String userPhone = tokenService.getLoginUserWeb(ServletUtils.getRequest()).getUser().getUserName();
        TUser tUser = tUserService.getUserByPhone(userPhone);
        Long tgCountByUserId = tUserService.getTgCountByUserId(tUser.getUserId());
        tUser.setTgNumOfPeople(tgCountByUserId);
        SysDictData BATTLEQDZS = sysDictDataService.selectDictDataById(190L);
        SysDictData BATTLEJZZB = sysDictDataService.selectDictDataById(191L);
        tUser.setBattleQdzs(BATTLEQDZS.getDictValue());
        tUser.setBattleJzzb(BATTLEJZZB.getDictValue());
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("whether_show_mine_clearance");
        String whether_show_mine_clearance = sysConfig == null ? "0" : sysConfig.getConfigValue();
        tUser.setWhetherShowMineClearance(whether_show_mine_clearance);

        SysConfig sysConfig1 = sysConfigMapper.checkConfigKeyUnique("battle_copywriting");
        tUser.setBattleCopywriting(sysConfig1.getConfigValue());

        SysConfig sysConfig2 = sysConfigMapper.checkConfigKeyUnique("lucky_goods_copywriting");
        tUser.setLuckyGoodsCopywriting(sysConfig2.getConfigValue());

        SysConfig sysConfig3 = sysConfigMapper.checkConfigKeyUnique("compensate_show_switch");
        tUser.setCompensateShowSwitch(sysConfig3.getConfigValue());

        if (StringUtils.isNotEmpty(tUser.getUserPromotersId())){
            TUser tg = tUserService.selectTUserById(tUser.getUserPromotersId());
            tUser.setAnchorResignationStatus(tg.getAnchorResignationStatus());
        }
        SysConfig czMoneyRangeConfig = sysConfigMapper.checkConfigKeyUnique("cz_money_range");
        String czmonerange = czMoneyRangeConfig.getConfigValue();
        tUser.setCzMoneRange(czmonerange);
        return Response.success(tUser);
    }


    /**
     * 注册用户信息
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("web注册用户信息")
    @RequestMapping(name="注册用户信息",value="common/register",method = RequestMethod.POST)
    @Log(title = "web注册用户信息", businessType = BusinessType.INSERT)
    public  Response register(@RequestBody TUser user)
    {
        try {
            return tUserService.register(user);
        } catch (Exception e) {
            log.error("注册用户信息异常:{}",e.getMessage());
            return Response.error();
        }
    }

    /**
     * 判断手机号码是否已经注册
     * @param user
     * @return
     */
    @ApiOperation("web判断手机号码是否已经注册")
    @RequestMapping(name="判断手机号码是否已经注册",value="common/decidePhone",method = RequestMethod.GET)
    @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true)
    public Response decidePhone(@RequestParam(value = "userPhone",required = true) String userPhone)
    {
        try {
            return tUserService.decidePhone(userPhone);
        } catch (Exception e) {
            log.error("判断手机号码是否已经注册异常:{}",e.getMessage());
            return Response.error();
        }
    }

    /**
     * 通过手机号修改密码
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("web通过手机号修改密码")
    @RequestMapping(name="通过手机号修改密码",value="common/retrievePassword",method = RequestMethod.GET)
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code",value = "验证码" , dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "userPwd",value = "密码" , dataType = "String", paramType = "query", required = true),
    })
    public  Response retrievePassword(@RequestParam(value = "userPhone",required = true) String userPhone,
                                      @RequestParam(value = "code",required = true) String code,
                                      @RequestParam(value = "userPwd",required = true) String userPwd)
    {
        try {
            return tUserService.retrievePassword(userPhone,code,userPwd);
        } catch (Exception e) {
            log.error("通过手机号修改密码异常:{}",e.getMessage());
            return Response.error();
        }
    }

    /**
     * 短信验证码发送
     * @param user
     * @return
     */
    @ApiOperation("web短信验证码发送")
    @RequestMapping(name="短信验证码发送",value="common/sendNode",method = RequestMethod.GET)
    @ApiImplicitParam(name = "userPhone",value = "手机号码" ,dataType = "String", paramType = "query", required = true)
    public  Response sendNode(@RequestParam(value = "userPhone",required = true) String userPhone)
    {
        try {
            return tUserService.sendNode(userPhone);
        } catch (Exception e) {
            log.error("短信验证码发送异常:{}",e.getMessage());

            return Response.error();
        }
    }

    /**
     * 修改用户昵称
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("web修改用户昵称")
    @RequestMapping(name="修改用户昵称",value="updateUserName",method = RequestMethod.GET)
    @ApiImplicitParam(name = "userName",value = "用户昵称" , dataType = "String", paramType = "query", required = true)
    @Log(title = "web修改用户昵称", businessType = BusinessType.UPDATE)
    public  Response updateUserName(@RequestParam(value = "userName",required = true) String userName)
    {
        try {
            if (userName.length() > 8) {
                return Response.fail(Constants.FAILCODE,"昵称长度不能大于8位~");
            }
            if(!StringUtils.isSpecialChar(userName)){
                return Response.fail(Constants.FAILCODE,"昵称不能包含特殊字符！");
            }
            String userId = tokenService.getLoginUserId();
            return tUserService.updateUserName(userId,userName);
        } catch (Exception e) {
            log.error("修改用户基本信息异常:{}",e);
            return Response.error();
        }
    }

    /**
     * 修改用户交易链接
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("web修改用户交易链接")
    @RequestMapping(name="修改用户交易链接",value="updateUserUrl",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "steamID",value = "Steam交易链接" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code",value = "验证码" , dataType = "String", paramType = "query", required = true),
    })
    @Log(title = "web修改用户交易链接", businessType = BusinessType.UPDATE)
    public Response updateUserUrl(@RequestParam(value = "steamID",required = true)  String steamID,
                                  @RequestParam(value = "code",required = false)   String code)
    {
        TUser tUser = new TUser();
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userPhone = sysUser.getUserName();
        tUser.setUserPhone(userPhone);
        tUser.setSteamID(steamID);
        tUser.setCode(code);
        try {
            return tUserService.updateUserUrl(tUser);
        } catch (Exception e) {
            log.error("修改用户交易链接异常:{}",e);
            return Response.error();
        }
    }

    /**
     * 用户头像上传
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("web用户头像上传")
    @RequestMapping(name="用户头像上传",value="avatar",method = RequestMethod.POST)
    public  AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file)  throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
            if (loginUser == null) {
                return new AjaxResult(Constants.FAILCODE,"用户登录失效！");
            }
            String path = null;
            try {
                path = picUploadService.upload(file);
            } catch (Exception e) {
               return AjaxResult.error("上传图片失败");
            }

//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
//            //String ip = IpUtils.getLinuxLocalIp();
//            String path = picpath+avatar.substring(RuoYiConfig.getProfile().length()+1);
            // 更新缓存用户头像
            TUser user = new TUser();
            user.setUserPhone(loginUser.getUser().getUserName());
            user.setUserPic(path);
            user.setUpdateTime(DateUtils.getNowDate());

            if (tUserMapper.updatePassword(user)>0)
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", path);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(path);
                tokenService.setLoginUserWeb(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 修改邀请人
     * @param user
     * @return
     */
    @CheckSwitch
    @ApiOperation("修改邀请人")
    @RequestMapping(name="修改邀请人",value="updateInvitationCode",method = RequestMethod.GET)
    @ApiImplicitParam(name = "tgUserSelfCode",value = "推广人邀请码" , dataType = "String", paramType = "query", required = true)
    @Log(title = "修改邀请人", businessType = BusinessType.UPDATE)
    public Response updateInvitationCode(@RequestParam(value = "tgUserSelfCode",required = true) String tgUserSelfCode) {
        try {
            if(StringUtils.isEmpty(tgUserSelfCode)){
                return Response.fail(Constants.FAILCODE,"邀请码不能为空！");
            }
            String userId = tokenService.getLoginUserId();
            return tUserService.updateInvitationCode(userId, tgUserSelfCode);
        } catch (Exception e) {
            log.error("修改邀请码异常:{}", e);
            return Response.error();
        }
    }

    /**
     * 图片上传
     * @param file
     * @return
     */
    @ApiOperation("web后台图片上传")
    @RequestMapping(name="后台图片上传",value="avatarBack",method = RequestMethod.POST)
    public  AjaxResult avatarBack(@RequestParam("avatarfile") MultipartFile file)  throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
            if (loginUser == null) {
                return new AjaxResult(Constants.FAILCODE,"用户登录失效！");
            }
            String path = null;
            try {
                path = picUploadService.upload(file);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("上传图片异常，请联系管理员");
            }
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
//            String path = picpath+avatar.substring(RuoYiConfig.getProfile().length()+1);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", path);
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    @ApiOperation("web合作伙伴")
    @RequestMapping(name="合作伙伴",value="cooperativePartner",method = RequestMethod.GET)
    public  Response<Map> cooperativePartner()
    {
        String userId = tokenService.getLoginUserId();
        return tUserService.cooperativePartner(userId);
    }


//    @ApiOperation("web统计结果")
//    @RequestMapping(name="统计结果",value="common/homeCount",method = RequestMethod.GET)
//    public Response<Map> homeCount()
//    {
//        Map map = new HashMap();
//        Long registnum = tUserMapper.registeredNumber();
//        Long loginnum = tUserMapper.loginNumber();
//        Long openboxcount = tbBackpackService.openBoxTotal();
//
//        map.put("loginnum",loginnum);
//        map.put("registnum",registnum);
//        map.put("openboxcount",openboxcount);
//        return Response.success(map);
//    }


    @ApiOperation("web幸运饰品升级记录")
    @RequestMapping(name="幸运饰品升级记录",value="myGoodsUpgrateRecord",method = RequestMethod.GET)
    public Response<List<TGoodsUpgrate>> myGoodsUpgrateRecord()
    {
        String userId = tokenService.getLoginUserId();
        return Response.success(tUserService.myGoodsUpgrateRecord(userId));
    }

    /**
     * 实名认证
     */
    @CheckSwitch
    @ApiOperation(value="实名认证")
    @RequestMapping(name="实名认证",value="authentication",method = RequestMethod.GET)
    @Log(title = "web实名认证",businessType = BusinessType.INSERT)
    @Transactional
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idcard",value = "身份证号" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "realname",value = "真实姓名" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code",value = "验证码" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "phone",value = "手机号码" ,dataType = "String", paramType = "query", required = true),
    })
    public Response authentication(@RequestParam(value = "idcard",required = true) String idcard,
                                     @RequestParam(value = "realname",required = true) String realname,
                                     @RequestParam(value = "code",required = true) String code,
                                     @RequestParam(value = "phone",required = true) String phone){

        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userId = sysUser.getLoginUserId();
        TUser tUser = tUserService.selectTUserById(userId);
        return tUserService.authentication(idcard, realname, code, phone, tUser);
    }

    /**
     * 对战机器人列表
     */
    @ApiOperation(value="对战机器人列表")
    @RequestMapping(name="对战机器人列表",value="battleRobatList",method = RequestMethod.GET)
    public Response<List<TUser>> battleRobatList(){
        List<TUser> battleRobot = tUserService.selectBattleRobot(null);
        return Response.success(battleRobot);
    }

    @CheckSwitch
    @ApiOperation(value="设置客户端种子")
    @PutMapping("/setUserSeed/{userSeed}")
    public Response setUserSeed(@PathVariable(value = "userSeed",required = true) String userSeed){
        String userId = tokenService.getLoginUserId();
        if(StringUtils.isEmpty(userSeed) || userSeed.length() > 20){
            return Response.fail("客户端种子不能为空，长度最多20位");
        }
        return Response.success( tUserService.setUserSeed(userId,userSeed));
    }

    @ApiOperation(value="获取公共参数")
    @GetMapping("/common/common_params")
    public Map<String, Object> commomParams(){
        Map<String, Object> map = new HashMap<>();
        SysConfig sysConfig1 = sysConfigMapper.checkConfigKeyUnique("battle_copywriting");
        map.put("battleCopywriting",sysConfig1.getConfigValue());

        SysConfig sysConfig2 = sysConfigMapper.checkConfigKeyUnique("lucky_goods_copywriting");
        map.put("luckyGoodsCopywriting",sysConfig2.getConfigValue());

        SysConfig sysConfig3 = sysConfigMapper.checkConfigKeyUnique("compensate_show_switch");
        map.put("compensateShowSwitch",sysConfig3.getConfigValue());

        SysConfig premium_rate_config = sysConfigMapper.checkConfigKeyUnique("luck_accessory_upgrade_premium_rate");
        map.put("luckAccessoryUpgradePremiumRate",premium_rate_config.getConfigValue());

        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("shutdown_switch");
        map.put("shutdownSwitch",sysConfig.getConfigValue());
        map.put("shutdownSwitchMsg",sysConfig.getRemark());
        return map;
    }
}
